class Solution:
    def longestValidParentheses(self, s: str) -> int:
        def check(s1, s2):
            return s1 == "(" and s2 == ")"
                 
        stack = []
        max_length = 0
        tmp = 0
        for i in s:
            print(i, "stack=",stack)
            if len(stack) == 0:
                stack.append(i)
            else:
                if i == ")": # 进行清理栈
                    if check(stack[-1], i):
                        tmp += 1
                        max_length = max(max_length, tmp)
                        stack = stack[:len(stack) -1]
                    else:
                        tmp = 0
                        stack = []
                else:
                    stack.append(i)
        return max_length * 2

def test():

    assert Solution().longestValidParentheses("(()") == 2
    assert Solution().longestValidParentheses(")()())") == 4
    assert Solution().longestValidParentheses("()(()") == 2

if __name__ == "__main__":
    Solution().longestValidParentheses("()(()")